/*
 * 天虹商场股份有限公司版权所有.
 */
package com.rainbow.formework.context.support;

import com.rainbow.formework.beans.HMKBeanDefinition;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * TODO
 *
 * @author 黄明坤
 * @version 1.0.0
 * @date 2020/7/3
 */
public class HMKBeanDefinitionReader {

    private Properties config = new Properties();

    private List<String> registyBeanClasses = new ArrayList<String>();

    //在配置文件中，用来获取自动扫描的包名的key
    private final String SCAN_PACKAGE = "scanPackage";

    public HMKBeanDefinitionReader(String... configLocations){
        //在Spring中是通过Reader去查找和定位对不对 locations[0].replace("classpath:","")
        InputStream is = null;
        try {
            is = new FileInputStream(new File("D:\\workspace\\ideaworkspace\\hmkSpring\\src\\main\\resources\\application.properties"));
            config.load(is);
        } catch (IOException exception) {
            exception.printStackTrace();
        } finally {
            try {
                if(null != is){is.close();}
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        doScanner(config.getProperty(SCAN_PACKAGE));

    }


    private void doScanner(String packageName) {
        URL url = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.","/"));

        File classDir = new File(url.getFile());

        for (File file : classDir.listFiles()){
            if(file.isDirectory()){
                doScanner(packageName + "." +file.getName());
            }else {
                registyBeanClasses.add(packageName + "." + file.getName().replace(".class",""));
            }
        }
    }

    public List<String> loadBeanDefinitions() {
        return this.registyBeanClasses;
    }

    public HMKBeanDefinition registerBean(String className) {
        if(this.registyBeanClasses.contains(className)){
            HMKBeanDefinition beanDefinition = new HMKBeanDefinition();
            beanDefinition.setBeanClassName(className);
            beanDefinition.setFactoryBeanName(lowerFirstCase(className.substring(className.lastIndexOf(".") + 1)));
            return beanDefinition;
        }

        return null;
    }

    private String lowerFirstCase(String str) {
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    public Properties getConfig(){
        return this.config;
    }
}
